sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel",
    "sap/ui/model/Filter",
    "sap/ui/model/FilterOperator",
    "sap/ui/model/FilterType",
],
    /**
     * @param {typeof sap.ui.core.mvc.Controller} Controller
     */
    function (Controller, JSONModel,Filter,FilterOperator,FilterType) {
        "use strict";

        return Controller.extend("ikdproject902.controller.Main", {
            onInit: function () {
                var json = {
                    "Matnr": '',
                    "Maktx": '',
                    "Meins": '',
                }

                var oModel = new JSONModel(json);
                this.getView().setModel(oModel, "crt");

                var oMessageManager = sap.ui.getCore().getMessageManager(),
                    oMessageModel = oMessageManager.getMessageModel(),
                    oMessageModelBinding = oMessageModel.bindList("/", undefined, [],
                        new Filter("technical", FilterOperator.EQ, true));

                oMessageModelBinding.attachChange(this.onMessageBindingChange, this);

            },
            onSaveButtonPress: function () {


                // var oCreate = new JSONModel(json);


                var aData = this.getView().getModel("crt").getData();
                // oBinding.create(aData, false);
                // debugger

                // var json = {
                //     "Matnr": 'GOOD',
                //     "Maktx": 'JOB',
                //     "Meins": '',
                // }

                var oTable = this.byId("itemTable");
                var oBinding = oTable.getBinding("items"); //get binding

                var oModel = this.getView().getModel();
                // var oBinding = oModel.bindList("/Mara")

                // oBinding.create(aData).then(
                //     function (res) {
                //         // oModel.refresh()
                //         alert('ok')
                //     },
                //     function (res) {
                //         alert(res)
                //     }
                // )

                oBinding.create(aData)
                // oContext.created().then(
                //     function (res) {
                //         // oModel.refresh()
                //         alert('ok')
                //     },
                //     function (res) {
                //         alert(res)
                //     }
                // )

                // this.getView().getModel().submitBatch("$auto").then(
                //     function (res) {
                //         oModel.refresh()
                //         // alert('ok')
                //     },
                //     function (res) {
                //         alert(res)
                //     }
                // )

                // debugger
            },
            onDeleteButtonPress: function () {
                var that = this
                var oTable = this.byId("itemTable")
                var selectedItems = oTable.getSelectedItems()
                var oModel = this.getView().getModel()

                selectedItems.forEach(item => {
                    var oContext = item.getBindingContext()
                    oContext.delete().then(
                        function (res) {
                            // oModel.refresh()
                            alert("ok")
                        },
                        function (res) {
                            alert("error")
                        })
                });
            },
            onDeleteCustom: function () {
                var aData = this.getView().getModel("crt").getData();

                var oModel = this.getView().getModel()
                //"/Mara('EEE')"
                // var oContext = oModel.bindContext("/Mara('" + aData.Matnr + "')")
                // var oContext = oModel.createBindingContext("/Mara('EEE')")
                // const contextBinding = oModel.bindContext("/Mara('ZZ')");
                // const targetContext = contextBinding.getBoundContext();
                // targetContext.delete().then(
                //     function (res) {
                //         // oModel.refresh()
                //         // alert("ok")
                //         oModel.submitBatch("$auto")
                //     },
                //     function (res) {
                //         // alert("error")
                //     }
                // )

                this.byId("saveBox").bindElement("/Mara('ZZZ')")
                var oContext3 = this.byId("saveBox").getBindingContext()
                oContext3.delete().then(
                    function (res) {
                        // oModel.refresh()
                        // alert("ok")
                    },
                    function (res) {
                        // alert("error")
                    }
                )

                // oModel.delete("/Mara('" + aData.Matnr + "')").then(
                //     function (res) {
                //         // oModel.refresh()
                //         alert("ok")
                //     },
                //     function (res) {
                //         alert("error")
                //     })
                // debugger

            },
            onUpdateButtonPress: function () {
                var that = this
                var oTable = this.byId("itemTable")
                var selectedItems = oTable.getSelectedItems()
                var oModel = this.getView().getModel()

                selectedItems.forEach(item => {
                    var oContext = item.getBindingContext()
                    oContext.setProperty("Maktx", '测试');
                });

                const contextBinding = oModel.bindContext("/Mara('ZZZ')");
                const targetContext = contextBinding.getBoundContext();
                targetContext.setProperty("Maktx", '555');
                // debugger

                // var oContext2 = oModel.bindContext("/Mara('ZZZ')")
                // oContext2.setProperty("Maktx", '111');

                // this.byId("saveBox").bindElement("/Mara('ZZZ')")
                // var oContext3 = this.byId("saveBox").getBindingContext()
                // oContext3.setProperty("Maktx", '444');
                // oContext2.change().then(
                //     function (res) {
                //         // oModel.refresh()
                //         alert("ok")
                //     },
                //     function (res) {
                //         alert("error")
                //     })
            },
            onStaticActionPress: function () {
                var that = this
                var oTable = this.byId("itemTable")
                var selectedItems = oTable.getSelectedItems()
                var oModel = this.getView().getModel()
                var oMetaModel = oModel.getMetaModel()
                // var oOperation = oModel.bindContext("/Mara/com.sap.gateway.srvd_a2x.zi_rap_nwf_090_sd.v0001.custom_action(...)");
                var oOperation = oModel.bindContext("/Mara/com.sap.gateway.srvd_a2x.zi_rap_nwf_090_sd.v0001.custom_actionwithp(...)");
                // debugger

                oOperation.setParameter("MATNR", "AAA");
                oOperation.execute().then(
                    function () {
                        alert('sourceResetSuccessMessage');
                    }.bind(this),
                    function (oError) {
                        alert(oError.message);
                    }
                )

            },
            onInstanceActionPress: function () {
                var that = this
                var oTable = this.byId("itemTable")
                var selectedItems = oTable.getSelectedItems()
                var oModel = this.getView().getModel()
                var oMetaModel = oModel.getMetaModel()

                // debugger

                selectedItems.forEach(item => {
                    var oContext = item.getBindingContext();
                    var oContext2 = oModel.bindContext("/Mara('A003')")

                    var oOperation = oModel.bindContext("com.sap.gateway.srvd_a2x.zi_rap_nwf_090_sd.v0001.normal_actionwithp(...)", oContext2);
                    oOperation.setParameter("MATNR", "AAA");
                    oOperation.execute().then(
                        function (oData) {
                            debugger
                            alert('sourceResetSuccessMessage');
                        }.bind(this),
                        function (oError) {
                            alert(oError.message);
                        }
                    )
                })
            },
            onReadPress: function () {
                var oModel = this.getView().getModel()
                var oContext = oModel.bindContext("/Mara('A003')")
                oContext.requestObject().then(function (oData) {
                    // 处理成功的回调
                    console.log("Data read successfully:", oData);
                }).catch(function (oError) {
                    // 处理失败的回调
                    console.error("Error reading data:", oError);
                });

            },
            onRefreshPress:function(){
                var oBinding = this.byId("itemTable").getBinding("items");
                oBinding.resetChanges();
                // debugger
                oBinding.refresh();
            },
            onMessageBindingChange: function (oEvent) {
                // debugger
                var aContexts = oEvent.getSource().getContexts(),
                    aMessages,
                    bMessageOpen = false;

                if (bMessageOpen || !aContexts.length) {
                    return;
                }

                // Extract and remove the technical messages
                aMessages = aContexts.map(function (oContext) {
                    return oContext.getObject();
                });
                sap.ui.getCore().getMessageManager().removeMessages(aMessages);

                // this._setUIChanges(true);
                // this._bTechnicalErrors = true;

                var oBinding = this.byId("itemTable").getBinding("items");
                oBinding.resetChanges();
                // debugger
                oBinding.refresh();

                // MessageBox.error(aMessages[0].message, {
                //     id: "serviceErrorMessageBox",
                //     onClose: function () {
                //         bMessageOpen = false;
                //     }
                // });

                bMessageOpen = true;
            }

        });
    });
